package com.MartynovichIgor.KnowledgeTest.tools.usertools;

import com.MartynovichIgor.KnowledgeTest.resources.ProjectPath;
import com.MartynovichIgor.KnowledgeTest.tools.filetools.FileLoader;
import com.MartynovichIgor.KnowledgeTest.tools.testtools.Parser;
import com.MartynovichIgor.KnowledgeTest.tools.testtools.Shuffler;
import com.MartynovichIgor.KnowledgeTest.tools.testtools.TestController;
import java.io.*;
import java.util.ArrayList;
import java.util.ResourceBundle;

/**
 * Created by:
 * User: Igor Martynovich and Guzenko Igor
 * Date: 25.10.13
 */
public class Loader {

    /**
     * Метод для загрузки вопросов для теста. Пробует загрузить с файла,
     * если не находит файл грузит с класса с информацией.
     * @param languageBundle
     * @return
     * @throws IOException
     */
    public ArrayList<String> loadedQuestions(ResourceBundle languageBundle) throws IOException {
        ArrayList<String> questionLines;
        try {
            String questionFields = new FileLoader().readFile(languageBundle.getString("filePath"));
            questionLines = getParsedQuestions(questionFields);
        } catch (FileNotFoundException e) {
            questionLines = (ArrayList<String>) languageBundle.getObject("sourceString");
        }
        return questionLines;
    }

    private ArrayList<String> getParsedQuestions(String questionFields) {
        return new Parser().getStringArray(questionFields, "\n");
    }

    /**
     * Метод загружает историю по логину и паролю.
     * @param userLogin
     * @param languageBundle
     * @return Обьект класса User созданый по логину и паролю с истории.
     * @throws IOException
     */
    public User loadUserInfo(String userLogin, ResourceBundle languageBundle) throws IOException {
        Parser parser = new Parser();
        User loadedUser = null;
        String allUsersInfo;
        try {
            allUsersInfo = new FileLoader().
                    readFile(new ProjectPath().getProjectPath()+ UserSaver.USER_INFO_FILE);
        } catch (IOException e) {
            return loadedUser;
        }
        ArrayList<String> usersInfoArray = parser.getStringArray(allUsersInfo, "\n");
        loadedUser = loadUserInfoFromFile(userLogin, usersInfoArray, languageBundle);
        return loadedUser;
    }

    private User loadUserInfoFromFile(String userLogin,ArrayList<String> usersInfoArray,
                                      ResourceBundle languageBundle) throws IOException {
        User loadedUser = null;
        Parser parser = new Parser();
        for (String userInfoLine : usersInfoArray) {
            ArrayList<String> userInfo = parser.getStringArray(userInfoLine, " ");
            if (userInfo.get(0).equals(userLogin)) {
                System.out.printf("\n%s", languageBundle.getString("pass"));
                BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
                String userPassword = reader.readLine();
                if (userInfo.get(1).equals(userPassword)) {
                    ArrayList<Integer> userPoints =parser.getIntArray(userInfo.get(3));

                    loadedUser = new User(userLogin, userPassword, parser.getIntArray(userInfo.get(2)),
                            userPoints, languageBundle, lastAnswer(userPoints));

                    if (loadedUser.getHistory().getCurrentQuestion() < 0) {
                        printLastScore(loadedUser, languageBundle);
                        loadedUser = getNewTestingUser(userLogin,userPassword,languageBundle);
                    }
                    break;
                }
            }
        }
        return loadedUser;
    }

    private User getNewTestingUser(String login, String password, ResourceBundle languageBundle) throws IOException {
        ArrayList<Integer> newIndexes = new Shuffler().getShuffledIndexses(TestController.COUNT_OF_QUESTIONS);
        return new User(login, password, newIndexes, TestController.getDefaultAnswersArray(),
                languageBundle, 0);
    }

    private void printLastScore(User user, ResourceBundle resourceBundle) {
        System.out.printf("%s %d", resourceBundle.getString("lastScore"), user.getScore());
        System.out.printf("%s", resourceBundle.getString("newStart"));
        System.out.println();

    }

    /**
     * Метод определяет позицию на которой вышли из теста.
     * @param answersPoint
     * @return Позицию выхода из теста.
     */
    private int lastAnswer(ArrayList<Integer> answersPoint) {
        for (int index = 0; index < answersPoint.size(); index++) {
            if (answersPoint.get(index) == -1) {
                return index;
            }
        }
        return -1;
    }

}
